import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/shop/life/GoodsListPage.dart';
import 'package:shop/shop/life/ServiceIndexPage.dart';
import 'package:shop/route/my_route.dart';
import 'MerchantListPage.dart';
import 'MerchantPage.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key key}) : super(key: key);

  @override
  _HomePage createState() => _HomePage();
}

class _HomePage extends State<HomePage> {
  FocusNode _focusNode = FocusNode(); // 焦点事件

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getGoodsFenye(); //得商品
    _getMerchantType(); //得商户类型
    _focusNode.addListener(() {
      if (!_focusNode.hasFocus) {
        // print('失去焦点');
      } else {
        // print('得到焦点');
        MyRoute.push(GoodsListPage(gName: "",sort: 0,type: 0,));
        _focusNode.unfocus();
      }
    });
  }

  List goodsTypes = []; //类型集合
  // _getGoodsType() async {
  //   var x = await HttpUtil().get("/app/goodsType/searchSigeYijiType");
  //   print(x);
  //   if (x['code'] == 200) {
  //     goodsTypes = x['data'];
  //   }
  //   setState(() {});
  // }

  //定义图片存储的数组
  // List _imageUrls = [
  //   "http://img.alicdn.com/imgextra/i4/6000000001151/O1CN01aX5NCk1KNCZJNCGLZ_!!6000000001151-0-lubanimage.jpg",
  //   "http://img.alicdn.com/imgextra/i3/6000000005498/O1CN01ZL8Ne81qU8GZ8JkUm_!!6000000005498-0-lubanimage.jpg"
  // ];
  int page = 1;
  int limit = 10;
  String gName = ""; //商品名称
  List list = []; //商品集合

  // 上拉加载控制器
  RefreshController _refreshController = RefreshController(initialRefresh: false);

  // 加载数据库的商品分页数据
  void _getGoodsFenye() async {
    // var x  = await HttpUtil().get("/app/goods/searchAllGoods?page=${page}&limit=${limit}");
    var x = await HttpUtil().get("/waimai/mGoods/queryMGoods?page=${page}&limit=${limit}");
    page++;
    if (x['code']==200) {
      list.addAll(x['data']);
      if(x['data'].length < 1){
        _refreshController.loadNoData();
        return;
      }
    }

    if(mounted){
      setState(() {});
      _refreshController.loadComplete();
    }
  }

  List merchantTypeList = []; //商户类型集合
  //得商户类型
  _getMerchantType() async {
    var x = await HttpUtil().get("/waimai/merchantType/searchAllMerchantType?type=0");
    if (x['code'] == 200) {
      merchantTypeList.addAll(x['data']);
    }
    setState(() {});
  }

  void _onRefresh() async {
    _refreshController.refreshCompleted();
  }

  // 加载数据的函数
  // void _onLoading() async {
  //   print("开始加载");
  //   var x  = await HttpUtil().get("/waimai/mGoods/queryMGoods?page=${page}&limit=2");
  //   if(x['data'].length>0) {
  //     list.addAll(x['data']);
  //     page++;
  //   }else{
  //     _refreshController.loadNoData();
  //     return;
  //   }
  //   if(mounted){
  //     setState(() {});
  //     _refreshController.refreshCompleted();
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 464, height: 820);
    return Scaffold(
      body: SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("上拉加载");
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("加载失败！点击重试！");
            } else if (mode == LoadStatus.canLoading) {
              body = Text("松手,加载更多!");
            } else {
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _getGoodsFenye,
        child: CustomScrollView(slivers: [
          SliverToBoxAdapter(
              child: Container(
            padding: EdgeInsets.only(top: 20),
            margin: EdgeInsets.only(bottom: 20),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(30)),
            ),
            child: Column(
              children: [
                Container(
                  width: ScreenUtil().setWidth(430),
                  height: ScreenUtil().setHeight(45),
                  margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(20)),
                    border: Border.all(color: Colors.orange, width: 1),
                  ),
                  child: Row(
                    children: [
                      // Icon(Icons.search,color: Colors.orange,),
                      Expanded(
                          child: Container(
                        child: TextField(
                          focusNode: _focusNode,
                          decoration: InputDecoration(
                            hintText: "搜索店家、餐名",
                            contentPadding:
                                EdgeInsets.fromLTRB(15, 0, 0, 6),
                            border: InputBorder.none,
                          ),
                          onChanged: (text) {
                            gName = text;
                          },
                        ),
                      )),
                      Container(
                        padding: EdgeInsets.fromLTRB(0, 0, 10, 0),
                        child: Icon(
                          Icons.search,
                          color: Colors.orange,
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                    margin: EdgeInsets.only(top: 20,bottom: 5),
                    child: Wrap(
                        direction: Axis.horizontal,
                        spacing: 20,
                        runSpacing: 10,
                        alignment: WrapAlignment.spaceAround,
                        children: _buildMerchantType(merchantTypeList)))
              ],
            ),
          )
              //   child:Container(
              //     margin: EdgeInsets.only(bottom: 10),
              //     child: Wrap(
              //         direction: Axis.horizontal,
              //         spacing: 20,
              //         runSpacing: 10,
              //         alignment: WrapAlignment.spaceAround,
              //         children:_buildMerchantType(merchantTypeList)
              //     )
              // )
              ),
          SliverList(
              delegate: SliverChildBuilderDelegate((content, index) {
            return GestureDetector(
              child: Container(
                color: Colors.white,
                margin: EdgeInsets.symmetric(horizontal: 10, vertical: 2),
                padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(15),
                      child: CachedNetworkImage(
                        imageUrl: Config.getInstance().getHost() +
                            list[index]['gimages'],
                        width: ScreenUtil().setWidth(111),
                        height: ScreenUtil().setHeight(111),
                      ),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(children: [
                            Expanded(
                              child: Text(
                                list[index]['gname'],
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.w500),
                              ),
                            )
                          ]),
                          // Text(item['jianjie']),
                          SizedBox(height: 10,),
                          Text(
                            "${list[index]['jianjie']}",
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(height: 10,),
                          Row(
                            children: [
                              Text(
                                "￥",
                                style: TextStyle(color: Colors.red),
                              ),
                              Text(
                                list[index]['gprice'].toString(),
                                style: TextStyle(
                                    color: Colors.red, fontSize: 18),
                              )
                            ],
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
              onTap: () {
                // print("跳转到详情");
                list[index]['mgoodsType']['merchantType']['type'] == 0
                  ? MyRoute.push(MerchantPage(
                      merchantId: list[index]['mid'],
                      merchantTypeId: list[index]['mgoodsType']['mtype'],
                    ))
                  : MyRoute.push(ServiceIndexPage(
                      mId: list[index]['mid'],
                    )
                );
              },
            );
          }, childCount: list.length))
        ])
      )
    );
  }

  @override
  void dispose() {
    _focusNode.unfocus();
    super.dispose();
  }

  // 显示商品类型
  _buildMerchantType(merchantTypeList) {
    List<Widget> x = [];
    for (int i = 0; i < merchantTypeList.length; i++) {
      x.add(GestureDetector(
        child: Column(
          children: [
            Container(
              height: i == 0 || i == 1 || i == 2 || i == 3
                  ? ScreenUtil().setHeight(65)
                  : ScreenUtil().setHeight(45),
              width: i == 0 || i == 1 || i == 2 || i == 3
                  ? ScreenUtil().setWidth(65)
                  : ScreenUtil().setWidth(45),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  image: new DecorationImage(
                    image: new NetworkImage(Config.getInstance().getHost() +
                        merchantTypeList[i]['picture']),
                  )),
            ),
            Text(merchantTypeList[i]['name'],
                style: TextStyle(decoration: TextDecoration.none))
          ],
        ),
        onTap: () {
          MyRoute.push(
              MerchantListPage(merchantTypeId: merchantTypeList[i]['id']));
        },
      ));
    }
    return x;
  }
}
